import '../../root.css';
import { mainStyle } from './login.css';
import SVGAccount from '@mdi/svg/svg/account.svg';
import SVGKey from '@mdi/svg/svg/key.svg';
import axios, { AxiosError } from 'axios';
import { Icon } from '@knno/jsx-ui/components/icon';
import { vars } from '@knno/jsx-ui/theme.css';
import { render } from '@knno/jsx';

export function getErrMsg(error: unknown): string {
	if (error instanceof AxiosError && error.response) {
		const { response } = error;
		return response.status + ': ' + response.data;
	} else if (error instanceof Error) {
		return error.message;
	} else {
		return `${error}`;
	}
}

render(() => {
	let msgDiv: HTMLDivElement;
	let account: HTMLInputElement;
	let pwd: HTMLInputElement;
	return (<main class={mainStyle}>
		<h1>DEMO</h1>
		<div class="panel">
			<h2>Welcome</h2>
			<div class="input">
				<div class="line">
					<Icon svg={SVGAccount} style={{ fill: vars.color.placeholderText, marginRight: '1em' }} size="1em" />
					<input spellcheck="false" placeholder="account" ref={(el) => (account = el)} value="admin" />
				</div>
				<div class="line" style={{ borderTop: '1px solid #ddd' }}>
					<Icon svg={SVGKey} style={{ fill: vars.color.placeholderText, marginRight: '1em' }} size="1em" />
					<input spellcheck="false" type="password" placeholder="password" ref={(el) => (pwd = el)} value="admin" />
				</div>
			</div>
			<button
				onclick={async () => {
					try {
						await axios.post('/api/auth/login', { account: account.value, password: pwd.value });
						msgDiv.textContent = '';
						location.href = '/';
					} catch (e) {
						msgDiv.textContent = getErrMsg(e);
					}
				}}>
				Login
			</button>
			<div
				class="error"
				ref={(el) => {
					msgDiv = el;
				}}></div>
		</div>
	</main>);
});
